﻿using ComLib.ComType;
using KeyboardArg;
using KInterfaces;
using KXmlUIControl.KControl;
using KXmlUIControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using ComUIControl;
using KeyboardFactory;
using LogLib;
using Mp3Player;

namespace KWindow.KPageCore
{
    public partial class PageControlBase
    {    
        /// <summary>
        /// 进入页面的时间
        /// </summary>
        public DateTime EntryTime { get; protected set; }

        /// <summary>
        /// 离开页面的时间
        /// </summary>
        public DateTime LeaveTime { get; protected set; }

        /// <summary>
        /// 指示页面是否已经关闭
        /// </summary>
        public bool IsClose { protected set; get; } = false;

        /// <summary>
        /// 指示页面的控件是否已经完成初始化
        /// </summary>
        public bool Initialized { protected set; get; } = false;

        /// <summary>
        /// 业务处理结果
        /// </summary>
        public bool HandleResult
        {
            protected set;
            get;
        }

        public UserApplyAction UserAction
        {
            get
            {
                if (_config != null)
                {
                    return _config.WorkFlow.ApplyType;
                }
                return UserApplyAction.Unknow;
            }
        }

        protected const int PhotosCount = 2;

        public void SetProcessBase<T>(PageProcessBase<T> process) where T : class
        {
            Process = process;
            HandleId = this.Handle.ToString();
            process.AddPage(this);
        }

        public IPageProcess Process
        {
            get;
            protected set;
        }

        public ShareData SD
        {
            get
            {
                if (Process != null)
                {
                    return Process.SD;
                }
                return null;
            }
        }

        protected PageConfigService _config = null;
  
        protected virtual void btnBack_Click(object sender, EventArgs e)
        {
            ClearData();
            Process.ToLast();
        }

        protected virtual void btnNext_Click(object sender, EventArgs e)
        {
            UpdateData();
            ClearData();
            Log.WriteAsync($"{Process.PageName}=>点击了下一步");
            Process.ToNext();
        }

        protected virtual void btnCancel_Click(object sender, EventArgs e)
        {
            ClearData();
            Process.ToHome();
        }

        protected virtual void SetTip(string content)
        {
            if (labelTitle != null)
            {
                string tipContent = content;
                if (tipContent.Contains("\\n"))
                {
                    tipContent = tipContent.Replace("\\n", "\n");
                }
                Process.SetTip(tipContent, labelTitle.Font.Size);
            }
            else
            {
                Process.SetTip("", 32);
            }
        }

        //初始化窗体数据
        public virtual void InitData()
        {
            EntryTime = LogConfig.Now();
            HandleResult = false;
            if (labelTitle != null)
            {
                SetTip(labelTitle.Text);
            }
            else
            {
                SetTip("");
            }
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public virtual void UpdateData()
        {

        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public virtual void ClearData()
        {
            if (textMapService != null)
            {
                textMapService.ClearData();
            }
            if (TextBoxs != null)
            {
                for (int i = 0; i < TextBoxs.Count; i++)
                {
                    TextBoxs[i].Text = "";
                }
            }
            if (ContainsGroup && CheckBoxs != null)
            {
                foreach (KCheckBox box in CheckBoxs)
                {
                    box.Checked = false;
                }
            }
            HandleResult = false;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public virtual void Close()
        {
            if(countdownControl1 != null)
            {
                if (CountdownEnabled || countdownControl1.IsRunning)
                {
                    countdownControl1.CloseCountDown();
                }
            }
           
            Log.WriteAsync("====================[" + GetAppName() + "Close]====================");
            IsClose = true;
        }

        public virtual void StartWork()
        {
          
        }

        public virtual void StopWork()
        {
            StopCountdown();
            LeaveTime = LogConfig.Now();
        }

        public virtual void AbortWork()
        {
            StopCountdown();
            LeaveTime = LogConfig.Now();
        }

        // Countdown
        public virtual void StartCountdown()
        {
            if(this.InvokeRequired)
            {
                Action handler = new Action(this.StartCountdown);
                this.Invoke(handler);
                return;
            }
            if(countdownControl1 != null)
            {
                countdownControl1.Visible = true;
                countdownControl1.Restart(CountdownSecond, OnCountdownCompleted);
            }           
        }

        public virtual void SuspendCountdown()
        {
            if(countdownControl1 != null)
            {
                countdownControl1.Start(OnCountdownCompleted);
            }            
        }

        public virtual void StopCountdown()
        {
            try
            {
                if (this.InvokeRequired)
                {
                    Action handler = new Action(this.StopCountdown);
                    this.Invoke(handler);
                    return;
                }
                if (countdownControl1 != null)  // && countdownControl1.IsRunning
                {
                    Log.WriteAsync($"{this.Name} 停止倒计时.");
                    countdownControl1.Stop();
                }
            }
            catch(Exception ex)
            {
                Log.WriteException(ex.ToString());
            }
        }

        public virtual void OnCountdownCompleted(object sender, EventArgs e)
        {            
            if (Process.IsRunning)
            {
                AbortWork();
                var ts = (LeaveTime - EntryTime).TotalSeconds;
                if (ts > 0 && (Math.Abs(ts - this.CountdownSecond) < 5 && ts >= 3))
                {
                    ClearData();
                    Log.WriteAsync($"倒计时结束，从{this.Name}回到主页");
                    Process.ToHomeApp();
                }
                else
                {
                    Log.WriteAsync($"{this.Name}的倒计时意外执行结束事件: EntryTime:{EntryTime}, LeaveTime:{LeaveTime}");
                }
            }
        }

        protected void ShowErrorMessage(string msg)
        {
            MsgBox box = new MsgBox(msg);
            box.ShowDialog(this);
        }

    }
}
